/*
 * Powered By [rapid-framework]
 * Web Site: http://www.rapid-framework.org.cn
 * Google Code: http://code.google.com/p/rapid-framework/
 * Since 2008 - 2012
 */


package com.smg.community.controller;

import java.util.HashMap;
import java.util.Map;

import javacommon.base.BaseRestSpringController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.org.rapid_framework.page.Page;

import com.smg.community.model.SmgMember;
import com.smg.community.model.SmgMemberFocus;
import com.smg.community.model.SmgMemberFriend;
import com.smg.community.model.SmgMessage;
import com.smg.community.vo.query.SmgMessageQuery;
/**
 * @author badqiu email:badqiu(a)gmail.com
 * @version 1.0
 * @since 1.0
 */

@Controller
@RequestMapping("/message")
public class SmgMessageController extends BaseRestSpringController<SmgMessage,java.lang.Integer>{
	
		
		
		/**
		 *      isRead int , -- 是否已读  1-已读  0-未读
			    messageType  int,   -- 消息类型  1-普通消息  2-系统消息
			    actionType  int default 0 ,  -- 相应的动作类型     1-好友请求 
			    isDeal  int default 0   ,-- 对于actionType>0 0-未处理 1-已处理
		 * @param request
		 * @param model
		 * @param type
		 * @param isRead
		 * @param pageNumber
		 * @return
		 */
		@RequestMapping("/receive")
		public String receive(HttpServletRequest request,ModelMap model){
			return receive(request,model,0,2,1);
		}
		
	
		/**
		 *      isRead int , -- 是否已读  1-已读  0-未读
			    messageType  int,   -- 消息类型  1-普通消息  2-系统消息
			    actionType  int default 0 ,  -- 相应的动作类型     1-好友请求 
			    isDeal  int default 0   ,-- 对于actionType>0 0-未处理 1-已处理
		 * @param request
		 * @param model
		 * @param type
		 * @param isRead
		 * @param pageNumber
		 * @return
		 */
		@RequestMapping("/receive/{messageType}-{isRead}-{pageNumber}")
		public String receive(HttpServletRequest request,ModelMap model,
							 @PathVariable int messageType,
							 @PathVariable int isRead,
				             @PathVariable int pageNumber){
			SmgMember member = getLoginMember(request);
			if ( member == null){
				return toErrorPage(model, "您没有登录或者登录已超时");
			}
			setCommunityCommonModel(request, model);
			setHeadTabIndex(model, 6);
			int loginMemberId = member.getMemberId();
			SmgMessageQuery query = new SmgMessageQuery();
			query.setToMemberId(loginMemberId);
			query.setToIsValid(1);
			query.setIsRead(isRead == 2 ?null:isRead);
			query.setMessageType(messageType == 0?null:messageType);
			setStartAndLimit(query, pageNumber,25);
			Page<SmgMessage> page = smgMessageManager.findPage(query);
			model.addAttribute("page",page);
			model.addAttribute("messageType",messageType);
			model.addAttribute("isRead",isRead);
			model.addAttribute("pageNumber",pageNumber);
			return "/message/receive";
		}
		
		/**
		 *      isRead int , -- 是否已读  1-已读  0-未读
			    messageType  int,   -- 消息类型  1-普通消息  2-系统消息
			    actionType  int default 0 ,  -- 相应的动作类型     1-好友请求 
			    isDeal  int default 0   ,-- 对于actionType>0 0-未处理 1-已处理
		 * @param request
		 * @param model
		 * @param type
		 * @param isRead
		 * @param pageNumber
		 * @return
		 */
		@RequestMapping("/send")
		public String send(HttpServletRequest request,ModelMap model){
			return send(request,model,0,2,1);
		}
		@RequestMapping("/send/{messageType}-{isRead}-{pageNumber}")
		public String send(HttpServletRequest request,ModelMap model,
				 @PathVariable int messageType,
				 @PathVariable int isRead,
	             @PathVariable int pageNumber){
			SmgMember member = getLoginMember(request);
			if ( member == null){
				return toErrorPage(model, "您没有登录或者登录已超时");
			}
			setCommunityCommonModel(request, model);
			setHeadTabIndex(model, 6);
			int loginMemberId = member.getMemberId();
			SmgMessageQuery query = new SmgMessageQuery();
			query.setFromMemberId(loginMemberId);
			query.setFromIsValid(1);
			query.setIsRead(isRead == 2 ?null:isRead);
			query.setMessageType(messageType == 0?null:messageType);
			setStartAndLimit(query, pageNumber,25);
			Page<SmgMessage> page = smgMessageManager.findPage(query);
			model.addAttribute("page",page);
			model.addAttribute("messageType",messageType);
			model.addAttribute("isRead",isRead);
			model.addAttribute("pageNumber",pageNumber);
			return "/message/send";
		}
		
		@RequestMapping("/detail/{id}")
		public String detail(HttpServletRequest request,ModelMap model,
				@PathVariable int id,
				@RequestParam String from){
			SmgMember member = getLoginMember(request);
			if ( member == null){
				return toErrorPage(model, "您没有登录或者登录已超时");
			}
			setCommunityCommonModel(request, model);
			setHeadTabIndex(model, 6);
			SmgMessage message = smgMessageManager.getById(id);
			if ( message == null){
				return toErrorPage(model, "您查看的消息不存在或者已经被删除");
			}
			if (message.getToMemberId() == member.getMemberId()) {
				smgMessageManager.setMessageIsRead(id+"");
			}
			model.addAttribute("message",message);
			model.addAttribute("from",from);
			return "/message/detail";
		}
		
		@RequestMapping("/newmessage")
		public String newMessage(HttpServletRequest request,ModelMap model,
	             @RequestParam(required=false) Integer memberId){
			SmgMember member = getLoginMember(request);
			if ( member == null){
				return toErrorPage(model, "您没有登录或者登录已超时");
			}
			setCommunityCommonModel(request, model);
			setHeadTabIndex(model, 6);
			String nickName = "";
			if ( memberId == null){
				
			}else{
				SmgMember tomember = smgMemberManager.getById(memberId);
				if ( member != null ){
					nickName = tomember.getNickName();
				}
			}
			model.addAttribute("nickName",nickName);
			return "/message/newmessage";
		}
		
		@RequestMapping("/setisread")
		public void setIsRead(HttpServletRequest request,ModelMap model,HttpServletResponse response){
			SmgMember member = getLoginMember(request);
			if ( member == null){
					writeErrorMessage(response);
					return ;
			}
			setCommunityCommonModel(request, model);
			setHeadTabIndex(model, 6);
			String checkedMessageIds = request.getParameter("checkedMessageIds");
			smgMessageManager.setMessageIsRead(checkedMessageIds);
			writeSuccessMessage(response);
		}
		
		@RequestMapping("/deletereceive")
		public void deleteReceive(HttpServletRequest request,ModelMap model,HttpServletResponse response){
			SmgMember member = getLoginMember(request);
			if ( member == null){
					writeErrorMessage(response);
					return ;
			}
			setCommunityCommonModel(request, model);
			setHeadTabIndex(model, 6);
			String checkedMessageIds = request.getParameter("checkedMessageIds");
			smgMessageManager.deleteReceive(checkedMessageIds);
			writeSuccessMessage(response);
		}
		
		
		  
		@RequestMapping("/deletesend")
		public void deleteSend(HttpServletRequest request,ModelMap model,HttpServletResponse response){
			SmgMember member = getLoginMember(request);
			if ( member == null){
					writeErrorMessage(response);
					return ;
			}
			setCommunityCommonModel(request, model);
			setHeadTabIndex(model, 6);
			String checkedMessageIds = request.getParameter("checkedMessageIds");
			smgMessageManager.deleteSend(checkedMessageIds);
			writeSuccessMessage(response);
		}
		  @RequestMapping({"/sendaction"})
		  @ResponseBody
		  public Map<String, Object> sendAction( @RequestParam String nickNames,HttpServletRequest request,SmgMessage message)
		  {
		    Map<String,Object> resultMap = new HashMap<String,Object>();
		    try {
		      SmgMember fromMember = getLoginMember(request);
		      if ( fromMember == null){
		    	  resultMap.put("state", "-1");
			      resultMap.put("desc", "您未登录或者登录已超时");
		    	  return resultMap;
		      }
		      String messageTitle = request.getParameter("messageTitle");
		      String messageCont = request.getParameter("messageCont");
		      if ( nickNames.trim().length() == 0){
				}
				nickNames = nickNames.replaceAll("；",";");
				String[] nickNameArray = nickNames.split(";");
				for(String nickName:nickNameArray){
				  	 nickName = nickName.trim();
					 SmgMember toMember = smgMemberManager.getByNickname(nickName);
					 if ( toMember == null){
					 }else{
					      message = new SmgMessage();
					      message.setActionType(0);
					      message.setMessageCont(messageCont);
					      message.setMessageTitle(messageTitle);
					      message.setFromMemberHeadImage(fromMember.getHeadImage());
					      message.setFromMemberId(fromMember.getMemberId());
					      message.setFromMemberNickName(fromMember.getNickName());
					      message.setMessageType(Integer.valueOf(1));
					      message.setToMemberHeadImage(toMember.getHeadImage());
					      message.setToMemberId(toMember.getMemberId());
					      message.setToMemberNickName(toMember.getNickName());
					      this.smgMessageManager.save(message);
					 }
		      resultMap.put("state", "1");
		      resultMap.put("desc", "调用接口成功");
				}
			} catch (Exception e) {
		      e.printStackTrace();
		      resultMap.put("state","-99");
		      resultMap.put("desc", "运行时错误");
		    }
		    return resultMap;
		  }


		  @RequestMapping({"/dealAddfrindMessage"})
		  @ResponseBody
		  public Map<String, Object> dealAddfrindMessage(@RequestParam String mid, @RequestParam String result)
		  {
		    Map resultMap = new HashMap();
		    try {
		      SmgMessage message = (SmgMessage)this.smgMessageManager.getById(Integer.valueOf(Integer.parseInt(mid)));
		      SmgMember fromMember = (SmgMember)this.smgMemberManager.getById(message.getFromMemberId());
		      SmgMember toMember = (SmgMember)this.smgMemberManager.getById(message.getToMemberId());
		      String toMemberNickName = toMember.getNickName();
		      String fromMemberNickName = fromMember.getNickName();
		      message.setIsRead(1);
		      message.setIsDeal(1);
		      if (result.equals("1"))
		        message.setActionResult(toMemberNickName + "通过了你的好友请求");
		      else if (result.equals("0"))
		        message.setActionResult(toMemberNickName + "拒绝了你的好友请求");

		      this.smgMessageManager.update(message);
		      SmgMessage newMessage = new SmgMessage();
		      newMessage.setActionType(0);
		      newMessage.setFromMemberHeadImage(toMember.getHeadImage());
		      newMessage.setFromMemberId(toMember.getMemberId());
		      newMessage.setFromMemberNickName(toMember.getNickName());
		      if (result.equals("1")) {
		        newMessage.setMessageCont(toMemberNickName + "通过了你的好友请求");
		        newMessage.setMessageTitle(toMember.getNickName() + "通过了你的好友请求");
		        SmgMemberFriend friend = new SmgMemberFriend();
		        friend.setMemberIdA(fromMember.getMemberId());
		        friend.setMemberIdB(toMember.getMemberId());
		        this.smgMemberFriendManager.save(friend);
		        SmgMemberFocus focus = new SmgMemberFocus();
		        if (this.smgMemberFocusManager.getByMemberIdAndFocuseId(fromMember.getMemberId(), toMember.getMemberId()) == null) {
		          focus.setFromMemberId(fromMember.getMemberId());
		          focus.setFocusMemberId(toMember.getMemberId());
		          this.smgMemberFocusManager.save(focus);
		        }

		        if (this.smgMemberFocusManager.getByMemberIdAndFocuseId(toMember.getMemberId(), fromMember.getMemberId()) == null) {
		          focus.setFromMemberId(toMember.getMemberId());
		          focus.setFocusMemberId(fromMember.getMemberId());
		          this.smgMemberFocusManager.save(focus);
		        }
		      } else if (result.equals("0")) {
		        newMessage.setMessageCont(toMemberNickName + "拒绝了你的好友请求");
		        newMessage.setMessageTitle(toMember.getNickName() + "拒绝了你的好友请求");
		      }

		      newMessage.setMessageType(1);
		      newMessage.setToMemberHeadImage(fromMember.getHeadImage());
		      newMessage.setToMemberId(fromMember.getMemberId());
		      newMessage.setToMemberNickName(fromMember.getNickName());
		      this.smgMessageManager.save(newMessage);
		      resultMap.put("state", "1");
		      resultMap.put("desc", "调用接口成功");
		    } catch (Exception e) {
		      e.printStackTrace();
		      resultMap.put("state", "-99");
		      resultMap.put("desc", "运行时错误");
		    }
		    return resultMap;
		  }
		

}



